import { useState } from "react";

function Square ({value, onSquareClick, isWinning}) {
    // 添加动态样式,当获胜时，对应索引的active改为true
    return <button className={'square ' + (isWinning ? 'square-active' : '')}  onClick={onSquareClick}>{value}</button>
}

export default function Game () {
    const [ history, setHistory ] = useState([{squares: Array(9).fill(null), moveLocation: null}])
    const [ currentMove, setCurrentMove ] = useState(0)
    // currentMove更新，xIsNext也会更新
    const xIsNext = currentMove % 2 === 0
    const currentSquares = history[currentMove] && history[currentMove].squares // 点击时光倒流，这里的数据是更新后指向最新的nextMove
    function handlePlay (nextSquares, squareIndex) {
        const row = Math.floor(squareIndex / 3) + 1;
        const col = (squareIndex % 3) + 1;
        const moveLocation = `row: ${row} col: ${col}`
        const nextHistory = [...history.slice(0, currentMove + 1), {
            squares: nextSquares,
            moveLocation
        }]
        // history里面记录所有的历史数据
        setHistory(nextHistory)
        // 更新最新的指针
        setCurrentMove(nextHistory.length - 1)
        // setXIsNext(!xIsNext)
    }

    function jumpTo (nextMove) {
        // 每次点击历史，history不会变
        setCurrentMove(nextMove)
        // X一定是偶数，O一定是奇数
        // setXIsNext(nextMove % 2 === 0)
    }
    console.log(history, 'history');
    const moves = history.map((squares, move) => {
        let description;
        if (move > 0) {
            // 必须知道新增的这颗旗子是第几行第几列
            description = 'Go to move #' + move + ' ' + squares.moveLocation
        } else {
            description = 'Go to game start'
        }
        return (
            <li key={move}>
                <button onClick={() => jumpTo(move)}>
                    {description}
                </button>
            </li>
        )
    })
    return (
        <div className="game-board">
            <div>
                <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay}  />
            </div>
            <div className="game-board">
                <ol>{moves}</ol>
            </div>
        </div>
    )
}
function Board({xIsNext, squares, onPlay}) {
    function handleClick (i) {
        const win = calculateWinner(squares)
        if (win && win.winner || squares[i]) {
            return
        }
        const nextSquares = squares.slice()
        if (xIsNext) {
            nextSquares[i] = 'X'
        } else {
            nextSquares[i] = 'O'
        }
        // 这两步状态更新是异步的，会放到下一次一起渲染
        onPlay(nextSquares, i)
        // 如果status和winner放在这里，则是拿到之前的状态更新的数据
    }
    let status = "Next player: " + (xIsNext ? "X" : "O");
    const win = calculateWinner(squares)
    if (win && win.winner) {
        status = win.winner + '获胜了'
    } else {
        status = "Next player: " + (xIsNext ? "X" : "O");
    }

    // 改造成用for循环来渲染井字棋
    let boardRows = []
    for (let row = 0; row < 3; row++) {
        const boardSquare = []
        for (let col = 0; col < 3; col++) {
            const squareIndex = row * 3 + col
            boardSquare.push(
                <Square key={squareIndex} isWinning={win && win.winnerLine.includes(squareIndex)} value={squares[squareIndex]} onSquareClick={() => handleClick(squareIndex)}></Square>
            )
        }
        boardRows.push(
            <div className="board-row" key={row}>
                {boardSquare}
            </div>
        )
    }
    // 如何重写
    return <>
        <div className="status">{status}</div>
        {boardRows}
    </>;
}

function calculateWinner (squares) {
    let lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ]

    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i]
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a],
                winnerLine: lines[i]
            }
        }
    }
    return null
}
